package com.olmarket.core.util;

/**
 * @author: qwesde@hust.edu.cn
 * @date: 2021/2/25 0:42
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 文件操作工具集合
 */
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 删除指定目录下的文件，文件夹
     *
     * @return
     */
    public static void emptyDir(File folder) {
        File[] files = folder.listFiles();
        if (null != files) {
            for (File file : files) {
                if (file.isDirectory()) {
                    emptyDir(file);
                } else {
                    file.delete();
                }
            }
        }
        folder.delete();
    }

    /**
     * unzip file
     */
    public static void unzip(File srcZippedFile, String destDirPath) throws Exception {
        long begin = System.currentTimeMillis();
        if (!srcZippedFile.exists()) {
            LOGGER.debug("unzip file not found!" + srcZippedFile.getPath());
            throw new RuntimeException(srcZippedFile.getPath() + " 文件不存在");
        }
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcZippedFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                if (entry.isDirectory()) {
                    (new File(destDirPath + "/" + entry.getName())).mkdirs();
                } else {
                    File file = new File(destDirPath + "/" + entry.getName());
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(file);
                    int len = 0;
                    byte[] buf = new byte[2048];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.close();
                    is.close();
                }
            }
            LOGGER.info("解压用时间：" + (System.currentTimeMillis() - begin) + " ms");
        } catch (IOException e) {
            throw new RuntimeException("解压失败! " + e.getMessage());
        } finally {
            if (null != zipFile) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    LOGGER.debug("关闭压缩文件失败！" + srcZippedFile.getPath());
                }
            }
        }
    }


}
